package com.example.component.Window;

import com.example.login.ILoginService;
import com.example.service.IService;
import com.example.service.IServiceManager;
import com.example.service.ServiceManager;
import com.vaadin.ui.Button;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Window;

@SuppressWarnings("serial")
public class LoginDialog extends Window {

	Button loginButton = null;
	TextField userNameInput = null;
	TextField passwordInput = null;
	Label statusMessage = null;
	
	public LoginDialog(){
		userNameInput = new TextField("User Name");
		passwordInput = new TextField("Password");
		passwordInput.setSecret(true);
		statusMessage = new Label("Please Login");
		loginButton = new Button("Login", this, "authenticateLogin");
		this.addComponent(userNameInput);
		this.addComponent(passwordInput);
		this.addComponent(loginButton);
		this.addComponent(statusMessage);
		
		setHeight("200px");
		setWidth("400px");
		setPositionX(200);
		setPositionY(50);
		this.setModal(true);
		this.setReadOnly(true);
	}
	
	public void authenticateLogin(Button.ClickEvent event){
		String username = (String)userNameInput.getValue();
		String password = (String)passwordInput.getValue();
		IServiceManager sm = ServiceManager.getInstance();
		ILoginService loginService = (ILoginService) sm.getService(IService.LOGINSERVICE);
		int loginReturn = loginService.validateLogin(username, password, this.getApplication());
		switch(loginReturn){
		case ILoginService.LOGIN_SUCCESS:{
			statusMessage.setValue("Login Success");
			Window myself = event.getButton().getWindow();
			Window myParent = (Window)myself.getParent();
			myParent.removeWindow(myself);
			break;
		}
		case ILoginService.ALREADY_LOGGEDIN:{
			statusMessage.setValue("User Already logged in");
			break;
		}
		case ILoginService.LOGIN_FAILED_BAD_PASSWORD:{
			statusMessage.setValue("Invalid Password");
			break;
		}
		default:{
			statusMessage.setValue("Login Failed");
			break;
		}
		}
	}
}
